package com.example.bluetoothchat.ui;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.bluetoothchat.R;
import com.example.bluetoothchat.base.BaseActivity;
import com.example.bluetoothchat.utils.BlueToothController;
import com.example.bluetoothchat.utils.ChatUtils;

import java.nio.charset.StandardCharsets;

public class MainActivity extends BaseActivity {

    private BlueToothController blueToothController;
    private ChatUtils chatUtils;

    private ListView lv;
    private LinearLayout bo;
    private EditText et;
    private TextView send;

    private ArrayAdapter<String> listAdapter;

    public static final int MESSAGE_STATE_CHANGE = 0X01;
    public static final int MESSAGE_READ = 0X02;
    public static final int MESSAGE_WRITE = 0X03;
    public static final int MESSAGE_DEVICE_NAME = 0X04;
    public static final int MESSAGE_TOAST = 0X05;

    public static final String DEVICE_NAME = "deviceName";
    public static final String TOAST = "toast";
    private String deviceName;


    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (message.arg1) {
                        case ChatUtils.STATE_NONE:
                            setState("未连接");
                            break;
                        case ChatUtils.STATE_LISTEN:
                            setState("未连接");
                            break;
                        case ChatUtils.STATE_CONNECTING:
                            setState("连接中...");
                            break;
                        case ChatUtils.STATE_CONNECTED:
                            setState("已连接："+ deviceName);
                            break;
                    }
                    break;
                case MESSAGE_READ:
                    byte[] buffer = (byte[]) message.obj;
                    String s = new String(buffer,0,message.arg1);
                    listAdapter.add(deviceName +":"+ s);
                    break;
                case MESSAGE_WRITE:
                    byte[] bytes = (byte[]) message.obj;
                    String str = new String(bytes,0,message.arg1);
                    listAdapter.add("me:"+ str);
                    break;
                case MESSAGE_DEVICE_NAME:
                    deviceName = (String) message.getData().get(DEVICE_NAME);
                    showToast(deviceName);
                    break;
                case MESSAGE_TOAST:
                    showToast((String) message.getData().get(TOAST));
                    break;
            }
            return false;
        }
    });

    private void setState(CharSequence subTitle){
        getSupportActionBar().setSubtitle(subTitle);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    showToast("OFF");
                    break;
                case BluetoothAdapter.STATE_ON:
                    showToast("ON");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    showToast("TURNING ON");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    showToast("TURNING OFF");
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {
        lv = (ListView) findViewById(R.id.lv);
        bo = (LinearLayout) findViewById(R.id.bo);
        et = (EditText) findViewById(R.id.et);
        send = (TextView) findViewById(R.id.send);

        listAdapter = new ArrayAdapter<>(MainActivity.this,R.layout.item);
        lv.setAdapter(listAdapter);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String target = et.getText().toString();
                if (!target.isEmpty()){
                    chatUtils.write(target.getBytes(StandardCharsets.UTF_8));
                }
            }
        });

        blueToothController = new BlueToothController(MainActivity.this);
        chatUtils = new ChatUtils(MainActivity.this,mHandler);
        IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver, intentFilter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search_bluetooth:
                checkPermission();
                return true;
            case R.id.bluetooth:
                checkBlueToothState();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void checkBlueToothState() {
        if (blueToothController.isSupportBlueTooth()) {
            if (!blueToothController.getBlueToothStatues()) {
                showToast("蓝牙未打开");
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Tips")
                        .setMessage("打开蓝牙")
                        .setPositiveButton("打开", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                blueToothController.turnOnBlueTooth(MainActivity.this, 0x01);
                            }
                        }).show();
            }
        } else {
            showToast("你的设备不支持蓝牙");
        }
    }

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0x01);
        } else {
            Intent intent = new Intent(MainActivity.this, BlueToothListActivity.class);
            startActivityForResult(intent, 0x02);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 0x01) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startActivity(new Intent(MainActivity.this, BlueToothListActivity.class));
            } else {
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("拒绝权限将无法使用程序")
                        .setPositiveButton("继续授权", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                checkPermission();
                            }
                        })
                        .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                MainActivity.this.finish();
                            }
                        }).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x01) {
            if (resultCode == RESULT_OK) {
                showToast("ON");
            } else {
                showToast("OFF");
            }
        } else if (requestCode == 0x02) {
            if (resultCode == RESULT_OK) {
                String adress = data.getStringExtra("adress");
                chatUtils.connect(blueToothController.getmAdapter().getRemoteDevice(adress));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        chatUtils.stop();
    }
}